<script>
// a class representing a dependency
// exposing it on window is necessary for testing
window.Dep = class Dep {
    constructor () {
      this.subscribers = new Set()
    }

    depend () {
      if (activeUpdate) {
        // register the current active update as a subscriber
        // 注册这个 activeUpdate 作为一个订阅者
        this.subscribers.add(activeUpdate)
        // 把 activeUpdate 添加到订阅者的依赖项中 
      }
    }

    notify () {
      // run all subscriber functions
      // 通知所有订阅者
      this.subscribers.forEach(subscriber => subscriber())
      console.log('notify')
    }
}

let activeUpdate

function autorun (update) {
  function wrappedUpdate () {
    activeUpdate = wrappedUpdate
    update()   // 确保内部 update 函数执行时 我们的依赖类可以访问这个activeUpdate
    activeUpdate = null
  }
  wrappedUpdate()
  // activeUpdate = update
  // update()
}

const dep = new Dep()
autorun(()=>{
  dep.depend()
  console.log('update')
})
dep.notify()
</script>
